package com.czk.netty.nio.basic;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * channel实现文件的拷贝
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/11 20:19
 */
public class ChannelTest2 {
    public static void main(String[] args) throws Exception {
        // 文件输入流
        FileInputStream fileInputStream = new FileInputStream("d:\\简历\\x.txt");
        // 拿到channel
        FileChannel channel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("d:\\简历\\2.txt");
        // 拿到channel
        FileChannel outputStreamChannel = fileOutputStream.getChannel();
        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int read = channel.read(buffer);
            if (read != -1) {
                // 切换状态
                buffer.flip();
                outputStreamChannel.write(buffer);
                // 重置标志位 不然position和limit相等，读到的都是read=0
                buffer.clear();
            } else {
                break;
            }
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
}
